<script>
import { defineComponent, watch, ref, computed, onUnmounted } from 'vue';
import { createNamespace } from '../utils';

export default defineComponent({
  name: createNamespace('Overlay')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true,
    },
    zIndex: {
      type: [String, Number],
      default: 1,
    },
    duration: {
      type: [String, Number],
      default: 0.3,
    },
    lockScroll: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['click'],
  setup(props, { emit }) {
    const theStyle = computed(() => {
      const { zIndex, duration } = props;
      return `z-index:${zIndex};--fan-overlay-time:${duration}s;`;
    });
    const isShow = ref(props.show);
    const className = ref('');
    // 显示动画
    const enter = (show) => {
      // #ifdef H5
      if (props.lockScroll) document.body.style = 'overflow: hidden';
      // #endif
      className.value = 'fan-overlay-enter-active';
      isShow.value = show;
      setTimeout(() => {
        className.value = '';
      }, props.duration * 1000);
    };
    // 隐藏动画
    const leave = (show) => {
      className.value = 'fan-overlay-leave-active';
      setTimeout(() => {
        isShow.value = show;
        // #ifdef H5
        if (props.lockScroll) document.body.style = '';
        // #endif
        className.value = '';
      }, props.duration * 1000);
    };
    // 关闭
    const close = () => emit('click');

    const onMove = () => {};

    onUnmounted(() => {
      // #ifdef H5
      document.body.style = '';
      // #endif
    });

    watch(
      () => props.show,
      (val, old) => {
        if (val === old) return;
        val ? enter(val) : leave(val);
      },
    );
    return {
      isShow,
      theStyle,
      className,
      close,
      onMove,
    };
  },
});
</script>

<template>
  <div v-if="isShow" class="fan-overlay" :class="className" :style="theStyle">
    <template v-if="lockScroll">
      <div
        style="width: 100%; height: 100%"
        @click="close"
        @touchmove.native.stop="onMove"
      >
        <slot />
      </div>
    </template>
    <template v-else>
      <div style="width: 100%; height: 100%" @click="close">
        <slot />
      </div>
    </template>
  </div>
</template>

<style lang="less">
.fan-overlay {
  --fan-overlay-time: 0.3s;

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.75);
}

.fan-overlay-enter-active {
  animation: var(--fan-overlay-time) fan-overlay-in both ease-in;
}

.fan-overlay-leave-active {
  animation: var(--fan-overlay-time) fan-overlay-out both ease-out;
}

@keyframes fan-overlay-in {
  0% {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes fan-overlay-out {
  0% {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}
</style>
